package com.xnx3.weixin.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.banmahuishou.core.entity.Agency;
import com.xnx3.banmahuishou.core.entity.Qishou;
import com.xnx3.banmahuishou.core.entity.WeixinPublicDlsOpenid;
import com.xnx3.banmahuishou.core.entity.WeixinPublicQishouOpenid;
import com.xnx3.banmahuishou.userApplet.controller.BaseController;
import com.xnx3.j2ee.entity.SmsLog;
import com.xnx3.j2ee.service.SmsService;
import com.xnx3.j2ee.service.SqlCacheService;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.service.UserService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.weixin.util.WeiXinUtil;

/**
 * 微信自动登录拿openid
 * @author 管雷鸣
 */
@Controller
@RequestMapping("/")
public class WXController  extends BaseController {

	@Resource
	private SqlService sqlService;
	@Resource
	private SqlCacheService sqlCacheService;
	@Resource
	private UserService userService;
	@Resource
	private SmsService smsService;
	
	
	/**
	 * 骑手绑定公众号
	 * 这个是在微信中点击的连接，微信中点击这个连接进入咱的系统，才能拿到对方用户的openid
	 */
	@RequestMapping("entry.do")
	public String entryActivity(HttpServletRequest request,Model model){
		String url = "http://"+request.getServerName()+"/wxAuthLoginBindPhone.do";	//后面可以带上get传递参数，如 ?a=1&b=2   注意，这里如果实际场景中做全站加速，request.getServerName() 是不准的，直接把域名在这里写死
		url = url.replaceAll("_3F","?").replaceAll("_26","&");	//URL转码
		System.err.println(url);
		String jumpUrl = WeiXinUtil.weixinUtil.getOauth2ExpertUrl(url);	//生成重定向的url，这个url只有在微信中才能打开，在普通浏览器是打不开的。 https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx07f3db3a6bbedfbe&redirect_uri=http://shop.imall.net.cn/plugin/weixinH5Auth/wxAuthLogin.do?storeid=1&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
		System.err.println(jumpUrl);
		ActionLogUtil.insert(request, "微信入口进入，重定向", jumpUrl);
		return "redirect:"+jumpUrl;
	}
	
	
	
	
	/**
	 * 骑手绑定公众号
	 * 微信登录 。 这里是用户访问 entry.do 然后跳转到微信授权，授权成功后自动跳转到的这里
	 * @param code 微信网页授权的code，微信授权url跳转时会自动传入过来
	 */
	@RequestMapping("wxAuthLoginBindPhone.do")
	public String wxAuthLoginBindPhone(HttpServletRequest request,Model model,
			@RequestParam(required = true) String code){
		System.out.println("进入微信登录#######code : " + code);
		ConsoleUtil.log(request.getQueryString());
		if(code.length() == 0){
			return "code未发现";
		}
		
		/**** 获取用户的openid ***/
		String openid = WeiXinUtil.weixinUtil.getOauth2OpenId(code);
		if(openid == null || openid.length() == 0){
			System.out.println("进入微信登录未拿到openid#######");
			return "获取用户openid失败";
		}
		
		/*
		 * 
		 * 
		 * 这里就已经拿到用户唯一的openid了
		 * 
		 * 
		 */
		ConsoleUtil.info("openid:"+openid);
		System.out.println("进入微信登录拿到openid####### : " + openid);
		
		model.addAttribute("openid", openid);
		return "/applet/wxAuthLoginBindPhone";
	}
	
	
	/**
	 * 发送短信验证码
	 * @param phone 要将验证码发送到哪个手机号
	 * @author 王晓龙
	 */
	@ResponseBody
	@RequestMapping(value="sendSmsCode.json", method= {RequestMethod.POST})
	public BaseVO sendSmsCode(HttpServletRequest request,
			@RequestParam(value = "phone", defaultValue="") String phone){
		//短信的内容。内容里六位数动态验证码用${code}表示
		String content = "你好，您登录手机号的验证码是${code}，请不要告知他人。";
		BaseVO vo = smsService.sendSms(request, phone, content, SmsLog.TYPE_LOGIN);
		if(vo.getResult() - BaseVO.SUCCESS == 0){
			ActionLogUtil.insert(request, "发送登录手机号验证码", phone);
		}else{
			ActionLogUtil.insert(request, "发送登录手机号验证码失败", "手机号:"+phone+",原因:"+vo.getInfo());
		}
		return vo;
	}
	
	
	
	/**
	 * 关联公众号和骑手openid
	 * @param openid	微信公众号用code兑换得骑手的openid
	 * @param phone		手机号
	 * @param code		验证码
	 * @author qyw
	 */
	@ResponseBody
	@RequestMapping(value="relationPublicQishouOpenid.json", method= {RequestMethod.POST})
	public BaseVO relationPublicQishouOpenid(HttpServletRequest request, @RequestParam("openid") String openid,
			@RequestParam(value = "phone", required = false, defaultValue="") String phone,
			@RequestParam(value = "code", required = false, defaultValue="") String code){
		
		System.out.println("进入关联公众号和骑手openid####### openid: " + openid);
		System.out.println("phone: " + phone);
		System.out.println("code: " + code);
		if (!StringUtils.hasLength(openid)) {
			return error("openid为空");
		}
		if (!StringUtils.hasLength(phone)) {
			return error("请填写手机号");
		}
		if (!StringUtils.hasLength(code)) {
			return error("请填写验证码");
		}
		//验证码校验
		BaseVO bvo = smsService.verifyPhoneAndCode(phone, code, SmsLog.TYPE_LOGIN, 300);
		if(bvo.getResult() - BaseVO.FAILURE == 0){
			ActionLogUtil.insert(request, "登录验证码错误:"+bvo.getInfo(), request.getQueryString());
			return error(bvo.getInfo());
		}
		Qishou user = sqlService.findAloneByProperty(Qishou.class, "phone", phone);
		if(user == null){
			return error("您不是骑手");
		}
		
		// 看看是否已绑定过
		WeixinPublicQishouOpenid findAloneByProperty = sqlService.findAloneByProperty(WeixinPublicQishouOpenid.class, "userid", user.getId());
		if (findAloneByProperty == null) {
			// 关联openid和用户id
			WeixinPublicQishouOpenid publicQishouOpenid = new WeixinPublicQishouOpenid();
			publicQishouOpenid.setOpenid(openid);
			publicQishouOpenid.setUserid(user.getId());
			sqlService.save(publicQishouOpenid);
		}else {
			return error("您已绑定骑手,无须重新绑定");
		}
		
		ActionLogUtil.insertUpdateDatabase(request, user.getId(), "关联公众号和骑手openid"); //记录日志
		return success();
	}
	
	
	/**
	 * 代理商绑定公众号
	 * 这个是在微信中点击的连接，微信中点击这个连接进入咱的系统，才能拿到对方用户的openid
	 */
	@RequestMapping("dlsEntry.do")
	public String dlsEntry(HttpServletRequest request,Model model){
		String url = "http://"+request.getServerName()+"/wxAuthLoginBindDls.do";	//后面可以带上get传递参数，如 ?a=1&b=2   注意，这里如果实际场景中做全站加速，request.getServerName() 是不准的，直接把域名在这里写死
		url = url.replaceAll("_3F","?").replaceAll("_26","&");	//URL转码
		System.err.println(url);
		String jumpUrl = WeiXinUtil.weixinUtil.getOauth2ExpertUrl(url);	//生成重定向的url，这个url只有在微信中才能打开，在普通浏览器是打不开的。 https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx07f3db3a6bbedfbe&redirect_uri=http://shop.imall.net.cn/plugin/weixinH5Auth/wxAuthLogin.do?storeid=1&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
		System.err.println(jumpUrl);
		ActionLogUtil.insert(request, "微信入口进入，重定向", jumpUrl);
		return "redirect:"+jumpUrl;
	}
	
	
	
	
	/**
	 * 代理商绑定公众号
	 * 微信登录 。 这里是用户访问 entry.do 然后跳转到微信授权，授权成功后自动跳转到的这里
	 * @param code 微信网页授权的code，微信授权url跳转时会自动传入过来
	 */
	@RequestMapping("wxAuthLoginBindDls.do")
	public String wxAuthLoginBindDls(HttpServletRequest request,Model model,
			@RequestParam(required = true) String code){
		System.out.println("进入微信登录#######code : " + code);
		ConsoleUtil.log(request.getQueryString());
		if(code.length() == 0){
			return "code未发现";
		}
		
		/**** 获取用户的openid ***/
		String openid = WeiXinUtil.weixinUtil.getOauth2OpenId(code);
		if(openid == null || openid.length() == 0){
			System.out.println("进入微信登录未拿到openid#######");
			return "获取用户openid失败";
		}
		
		/*
		 * 
		 * 
		 * 这里就已经拿到用户唯一的openid了
		 * 
		 * 
		 */
		ConsoleUtil.info("openid:"+openid);
		System.out.println("进入微信登录拿到openid####### : " + openid);
		
		model.addAttribute("openid", openid);
		return "/applet/wxAuthLoginBindDls";
	}
	
	
	/**
	 * 关联公众号和代理商的openid
	 * @param openid	微信公众号用code兑换的代理商的openid
	 * @param phone		手机号
	 * @param code		验证码
	 * @author qyw
	 */
	@ResponseBody
	@RequestMapping(value="relationPublicDlsOpenid.json", method= {RequestMethod.POST})
	public BaseVO relationPublicDlsOpenid(HttpServletRequest request,
			@RequestParam("openid") String openid,
			@RequestParam(value = "phone", required = false, defaultValue="") String phone,
			@RequestParam(value = "code", required = false, defaultValue="") String code){
		
		System.out.println("进入关联公众号和代理商openid####### openid: " + openid);
		System.out.println("phone: " + phone);
		System.out.println("code: " + code);
		if (!StringUtils.hasLength(openid)) {
			return error("openid为空");
		}
		if (!StringUtils.hasLength(phone)) {
			return error("请填写手机号");
		}
		if (!StringUtils.hasLength(code)) {
			return error("请填写验证码");
		}
		//验证码校验
		BaseVO bvo = smsService.verifyPhoneAndCode(phone, code, SmsLog.TYPE_LOGIN, 300);
		if(bvo.getResult() - BaseVO.FAILURE == 0){
			ActionLogUtil.insert(request, "登录验证码错误:"+bvo.getInfo(), request.getQueryString());
			return error(bvo.getInfo());
		}
		
		Agency user = sqlService.findAloneByProperty(Agency.class, "phone", phone);
		if(user == null){
			return error("您不是代理商");
		}
		
		// 看看是否已绑定过
		WeixinPublicDlsOpenid findAloneByProperty = sqlService.findAloneByProperty(WeixinPublicDlsOpenid.class, "userid", user.getUserid());
		if (findAloneByProperty == null) {
			// 关联openid和用户id
			WeixinPublicDlsOpenid weixinPublicDlsOpenid = new WeixinPublicDlsOpenid();
			weixinPublicDlsOpenid.setOpenid(openid);
			weixinPublicDlsOpenid.setUserid(user.getUserid());
			sqlService.save(weixinPublicDlsOpenid);
		}else {
			return error("您已绑定代理商,无须重新绑定");
		}
		ActionLogUtil.insertUpdateDatabase(request, user.getId(), "关联公众号和代理商openid"); //记录日志
		return success();
	}
	
	
}
